import { NestFactory } from '@nestjs/core';
import { type NestExpressApplication } from '@nestjs/platform-express';
import { HttpExceptionFilter } from './filters/http-exception';
import { TransformInterceptor } from './interceptor/transform.interceptor';
import * as path from 'path';
import * as fs from 'fs';

import { AppModule } from './app.module';

async function bootstrap() {
  const publicPath = path.join(__dirname, '..', 'public');

  if (!fs.existsSync(publicPath)) {
    fs.mkdirSync(publicPath);
  }

  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: ['error', 'warn', 'log'],
  });

  app.setGlobalPrefix('api');
  app.enableCors({
    origin: '*',
    exposedHeaders: ['Content-Disposition'],
    methods: ['PUT', 'POST', 'GET', 'DELETE', 'OPTIONS', 'HEAD'],
    allowedHeaders: [
      'Content-Type',
      'Content-Length',
      'Authorization',
      'Accept-Language',
      'Content-Language',
      'Accept',
      'X-Requested-With',
      'Origin',
      'Content-Disposition',
    ],
  });

  app.useStaticAssets(path.join(__dirname, '..', 'public'), {
    maxAge: '1d',
    extensions: ['jpg', 'jpeg', 'png', 'gif'],
    prefix: '/static',
  });

  app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalInterceptors(new TransformInterceptor());

  await app.listen(3000);
}

bootstrap();
